package org.example.service;

import org.elasticsearch.action.index.IndexRequest;
import org.example.model.User;
import org.example.repository.UserRepository;
import org.example.utils.UserUtils;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangy
 * @description
 * @since 2023/2/24 20:51
 **/
@Service
public class UserService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    public void addUser() {
        try {
            User user = UserUtils.createUser();
            userRepository.save(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * @description 通过id获取用户
     * @author huangy
     * @since 2023/2/15 14:55
     * @param id
     * @return org.example.model.User
     **/
    public User getUserById(long id){
        return userRepository.findById(id);
    }

    /*
     * @description 通过昵称获取用户
     * @author huangy
     * @since 2023/2/15 14:55
     * @param name
     * @return java.util.List<org.example.model.User>
     **/
    public List<User> getUsers(String name) {
        return userRepository.findByName(name);
    }

    /*
     * @description 获取所有用户信息
     * @author huangy
     * @since 2023/2/15 15:12
     * @return java.util.List<org.example.model.User>
     **/
    public List<User> getAllUses() {
        List<User> users = new ArrayList<>();
        Iterable<User> all = userRepository.findAll();
        for (User user : all) {
            users.add(user);
        }
        return users;
    }

    /*
     * @description 通过id更新数据
     * @author huangy
     * @since 2023/2/15 18:26
     * @param id
     **/
    public void updateById(long id) {
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.source("name", "如影随形");
        UpdateQuery updateQuery = UpdateQuery.builder(String.valueOf(id)).build();
    }
}
